/*******************************************************
 * @Title: GyroGuideActivity.java
 * @Package org.shangjiyu.gyroguide.activity
 * @Description: TODO(GyroGuide main activity)
 * @author shangjiyu@gmail.com
 * @date 2014-2-13 下午5:56:28
 * @version V1.0
 ********************************************************/

package org.shangjiyu.gyroguide.activity;

import org.shangjiyu.gyroguide.KiwiView.GyroGuideKiwiView;

import android.R.integer;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.kitware.KiwiViewer.InfoActivity;
import com.kitware.KiwiViewer.KiwiGLSurfaceView;
import com.kitware.KiwiViewer.KiwiViewerActivity;
import com.kitware.KiwiViewer.R;

/********************************************************
 * @ClassName: GyroGuideActivity
 * @Description: TODO(main activity)
 * @author shangjiyu
 * @date 2014-2-13 下午5:56:28
 */

public class GyroGuideActivity extends KiwiViewerActivity {

	public static final String TAG = "gyroguide activity";
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private ListView mDrawerList;
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
//    private GyroGuideKiwiView mView;
    
	/********************************************************
	 *Title: onCreate
	 *Description: 
	 * @param savedInstanceState
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 *********************************************************/
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
//		super.handleUriFromIntent(getIntent().getData());
		setContentView(R.layout.activity_gyroguide);
		mTitle = mDrawerTitle = getTitle();
		mView = (GyroGuideKiwiView) findViewById(R.id.gyroKiwiViewDefault);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        
        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // Set the adapter for the list view
        
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, super.mBuiltinDatasetNames));
        // Set the list's click listener
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
        
        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
        
        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(
        		this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
        		){
        	/********************************************************
        	 *Title: onDrawerClosed
        	 *Description: 
        	 * @param drawerView
        	 * @see android.support.v4.app.ActionBarDrawerToggle#onDrawerClosed(android.view.View)
        	 *********************************************************/
        	
        	@Override
        	public void onDrawerClosed(View drawerView) {
        		// TODO Auto-generated method stub
        		super.onDrawerClosed(drawerView);
        		getActionBar().setTitle(mTitle);
        		invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        	}
        	/********************************************************
			 *Title: onDrawerOpened
			 *Description: 
			 * @param drawerView
			 * @see android.support.v4.app.ActionBarDrawerToggle#onDrawerOpened(android.view.View)
			 *********************************************************/
			
			@Override
			public void onDrawerOpened(View drawerView) {
				// TODO Auto-generated method stub
				super.onDrawerOpened(drawerView);
				getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
			}
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        
        //start load dataset
        SharedPreferences prefs = getPreferences(MODE_PRIVATE);
        String versionStr = getString(R.string.version_string);
        if (!versionStr.equals(prefs.getString("version_string", ""))) {
            prefs.edit().putString("version_string", versionStr).commit();
            showWelcomeDialog();
        }else {
            maybeLoadDefaultDataset(mView);
        }
	}
	
	/********************************************************
	 *Title: onCreateOptionsMenu
	 *Description: 
	 * @param menu
	 * @return
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 *********************************************************/
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	/********************************************************
	 *Title: onOptionsItemSelected
	 *Description: 
	 * @param item
	 * @return
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 *********************************************************/
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		// The action bar home/up action should open or close the drawer.
        // ActionBarDrawerToggle will take care of this.
		if (mDrawerToggle.onOptionsItemSelected(item)) {
           return true;
		}
		// Handle action buttons
        switch(item.getItemId()) {
        case R.id.action_reset:
            mView.resetCamera(true);
            return true;
        case R.id.action_info:
        	Intent infoIntent = new Intent();
            infoIntent.setClass(GyroGuideActivity.this, InfoActivity.class);
            startActivity(infoIntent);
        	return true;
        case R.id.action_main:
        	Intent gyroMainIntent = new Intent();
        	gyroMainIntent.setClass(this, GyroguideMainActivity.class);
        	gyroMainIntent.putExtra(TAG, datasetToOpen);
        	startActivity(gyroMainIntent);
        	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
	}
	
	/* The click listener for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }
    
    private void selectItem(int position) {
    	if (mBuiltinDatasetNames.get(position).equals(getString(R.string.midas_text))) {
            openUrlInBrowser(getString(R.string.external_data_url));
          }
          else if (mBuiltinDatasetNames.get(position).equals(getString(R.string.download_file_text))) {
            showDownloadFileDialog(new String());
          }
          else if (mBuiltinDatasetNames.get(position).equals(getString(R.string.pvremote_text))) {
            doPVRemote();
          }
          else if (mBuiltinDatasetNames.get(position).equals(getString(R.string.pvweb_text))) {
            doPVWeb();
          }
          else if (mBuiltinDatasetNames.get(position).equals(getString(R.string.pointcloudstreaming_text))) {
            doPointCloudStreaming();
          }
          else {
            datasetToOpen = position;
            loadDataset(datasetToOpen);
          }
    	
        mDrawerList.setItemChecked(position, true);
        setTitle(mBuiltinDatasetNames.get(position));
        mDrawerLayout.closeDrawer(mDrawerList);
    }
    
    /********************************************************
     *Title: loadDataset
     *Description: 
     * @param filename
     * @see com.kitware.KiwiViewer.KiwiViewerActivity#loadDataset(java.lang.String)
     *********************************************************/
    
    @Override
    public void loadDataset(String filename) {
    	// TODO Auto-generated method stub
//    	super.loadDataset(filename);
    	showProgressDialog();
    	this.mView.loadDataset(filename, GyroGuideActivity.this);
    }
    
    /********************************************************
     *Title: loadDataset
     *Description: 
     * @param builtinDatasetIndex
     * @see com.kitware.KiwiViewer.KiwiViewerActivity#loadDataset(int)
     *********************************************************/
    
    @Override
    public void loadDataset(int builtinDatasetIndex) {
    	// TODO Auto-generated method stub
//    	super.loadDataset(builtinDatasetIndex);
    	//String filename = KiwiNative.getDatasetFilename(builtinDatasetIndex);
        String filename = mBuiltinDatasetNames.get(builtinDatasetIndex);

        if (filename.equals("pvweb")) {
          doPVWeb();
          return;
        }

        // don't attempt to open large asset files on android api 8
        int sdkVersion = Build.VERSION.SDK_INT;
        if (sdkVersion <= 8
            && (filename.equals("visible-woman-hand.vtp")
                || filename.equals("AppendedKneeData.vtp")
                || filename.equals("cturtle.vtp")
                || filename.equals("model_info.txt"))) {
          showCannotOpenAssetDialog();
          return;
        }
        
        new loadDatasetTask().execute(filename);
    }
    /********************************************************
     *Title: setTitle
     *Description: 
     * @param title
     * @see android.app.Activity#setTitle(java.lang.CharSequence)
     *********************************************************/
    
    @Override
    public void setTitle(CharSequence title) {
    	// TODO Auto-generated method stub
    	super.setTitle(title);
    	this.mTitle = title;
    	getActionBar().setTitle(title);
    }
    
    /********************************************************
     *Title: showProgressDialog
     *Description: 
     * @see com.kitware.KiwiViewer.KiwiViewerActivity#showProgressDialog()
     *********************************************************/
    
    @Override
    protected void showProgressDialog() {
    	// TODO Auto-generated method stub
    	this.showProgressDialog("data loading ...");
    }
    /********************************************************
     *Title: showProgressDialog
     *Description: 
     * @param message
     * @see com.kitware.KiwiViewer.KiwiViewerActivity#showProgressDialog(java.lang.String)
     *********************************************************/
    
    @Override
    protected void showProgressDialog(String message) {
    	// TODO Auto-generated method stub
    	//super.showProgressDialog(message);
    	Log.i(TAG, message+"in gyroguide activity");
    	this.mProgressDialog = new ProgressDialog(GyroGuideActivity.this);
    	this.mProgressDialog.setIndeterminate(true);
    	this.mProgressDialog.setCancelable(false);
    	this.mProgressDialog.setMessage(message);
    	this.mProgressDialog.show();
    }
    
    /********************************************************
     *Title: dismissProgressDialog
     *Description: 
     * @see com.kitware.KiwiViewer.KiwiViewerActivity#dismissProgressDialog()
     *********************************************************/
    
    @Override
    public void dismissProgressDialog() {
    	// TODO Auto-generated method stub
    	Log.i(TAG, "called dismissDialog in gyroguide");
//    	super.dismissProgressDialog();
    	if (this.mProgressDialog != null) {
    		this.mProgressDialog.dismiss();
		}
    }
    
    /********************************************************
     *Title: onResume
     *Description: 
     * @see com.kitware.KiwiViewer.KiwiViewerActivity#onResume()
     *********************************************************/
    
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    }
    
    class loadDatasetTask extends AsyncTask<String, integer, String>{

    	public int mBuiltinDatasetIndex;
        public String fileName;
        public KiwiGLSurfaceView view2load = mView != null?mView:null;
        public KiwiViewerActivity loaderActivity = GyroGuideActivity.this;
        
    	/********************************************************
		 *Title: doInBackground
		 *Description: 
		 * @param params
		 * @return
		 * @see android.os.AsyncTask#doInBackground(java.lang.Object[])
		 *********************************************************/
		
		@Override
		protected String doInBackground(String... filename) {
			// TODO Auto-generated method stub
			return copyAssetFileToStorage(filename[0]);
		}
		/********************************************************
		 *Title: onPreExecute
		 *Description: 
		 * @see android.os.AsyncTask#onPreExecute()
		 *********************************************************/
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			showProgressDialog();
		}
		
		/********************************************************
		 *Title: onPostExecute
		 *Description: 
		 * @param result
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 *********************************************************/
		
		@Override
		protected void onPostExecute(String filename) {
			// TODO Auto-generated method stub
			view2load.loadDataset(filename, -1, loaderActivity);
		}
    	
    }

}

